package cn.tedu.csmall.gateway.filters;

import cn.tedu.csmall.gateway.web.JsonResult;
import cn.tedu.csmall.gateway.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 网关gateway判断Headers的过滤器
 */
@Component
@Slf4j
public class MyFilter03 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("过滤器03执行！");
        // 在过滤器中拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 拿到响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 对request请求头获取
        HttpHeaders headers = request.getHeaders();
        // 拿到Host数据
        InetSocketAddress host = headers.getHost();
        log.info("从Api方法获取Host名：{}, 端口为：{}", host.getHostName(), host.getPort());
        // 从请求头中获取Authorization数据
        List<String> authorizationList = headers.get("Authorization");
        // TODO 修改其中手动拼接Json的过程,换成fasterJson 将对象实现api方法的json字符串转化

        // 对拿到的Authorization数据进行判断 这个数据如果是空或者长度为0
        if (authorizationList == null || authorizationList.size() == 0) {
            String message = "您当前未认证！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST, message);
            String jsonString = JSON.toJSONString(jsonResult);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.fromSupplier(() -> {
                // 数据流写进response
                return response.bufferFactory().wrap(jsonString.getBytes(StandardCharsets.UTF_8));
            }));
        } else {
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
